package xyz.eden.boot.ability.code.generate;

import lombok.extern.slf4j.Slf4j;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;
import xyz.eden.boot.ability.code.generate.enums.TemplateEngineType;

import java.util.Locale;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class ThymeleafTemplateFromText implements TemplateFactory {

    TemplateEngine templateEngine;

    @Override
    public void initTemplateEngine() {
        StringTemplateResolver templateResolver = new StringTemplateResolver();
        templateResolver.setCacheable(true);
        templateResolver.setTemplateMode(TemplateMode.TEXT);

        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        this.templateEngine = templateEngine;
    }

    @Override
    public boolean isSupper(TemplateEngineType engineType) {
        return Objects.equals(TemplateEngineType.THYMELEAF_FILE, engineType);
    }

    @Override
    public String processTemplate(String templateStr, Map<String, Object> dataMap) {
        try {
            Context context = new Context(Locale.CHINESE);
            context.setVariables(dataMap);
            return templateEngine.process(templateStr, context);
        } catch (Exception e) {
            log.error("ThymeleafTemplateFromText.processTemplate - template process exception.", e);
            return templateStr;
        }
    }
}
